import axios from "axios"
import { Message, Loading } from "element-ui"
import router from "./router"

let loading
function startLoading() {
    loading = Loading.service({
        lock: true,
        text: '拼命加载中...',
        background: 'rgba(0, 0, 0, 0.7)'
    })
}

function endLoading() {
    loading.close()
}

// 请求拦截
axios.interceptors.request.use(
    config => {
        // 加载动画
        startLoading()

        // 设置请求头
        if (localStorage.Token) {
            config.headers.Authorization = localStorage.Token
        }

        return config
    }, 
    err => {
        return Promise.reject(err)
    }
)

// 响应拦截
axios.interceptors.response.use(response => {
    endLoading()
    return response
}, error => {
    // 错误提醒
    endLoading()
    // Message.error(error.response.data)

    const { status } = error.response
    if (status == 401) {
        Message.error('token值无效，请重新登录')
        // 清除token
        localStorage.removeItem('Token')

        // 页面跳转
        router.push('/login')
    } else if (status === 400) {
        Message.error(error.response.data.msg)
        router.push('/register')
    }

    return Promise.reject(error)
})
export default axios